<template>
  <div v-if="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <div style="display: flex; align-items: center; margin: 16px 0 24px">
        <px-button type="primary" icon="ArrowLeft" style="margin-right: 16px" @click="backMainPage">返回</px-button>
        <px-tag
          v-if="props.drawerType !== 'add' && formValue.approvalStatus"
          effect="plain"
          :style="{
            color: `${tagColorList[formValue.approvalStatus]}`,
            border: `1px solid ${tagBorderColorList[formValue.approvalStatus]}`,
            backgroundColor: `${tagBgColorList[formValue.approvalStatus]}`
          }"
        >
          {{ formValue.approvalStatusDesc }}
        </px-tag>
      </div>
      <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <EditDropDown dropdownTitle="入库信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="8">
                <px-form-item label="入库类型" prop="sourceDesc">
                  <px-input v-model="formValue.sourceDesc" placeholder="自动带出入库类型" maxlength="50" clearable disabled />
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.source === 'back'" :span="8">
                <px-form-item label="还回原因" prop="backReason">
                  <px-input v-model="formValue.backReason" placeholder="请输入还回原因" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="入库单号" prop="inNum">
                  <px-input v-model="formValue.inNum" placeholder="自动生成入库单号" maxlength="50" clearable disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="入库主题" prop="inName">
                  <px-input v-model="formValue.inName" placeholder="请输入入库主题" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="归属地块" prop="facCode">
                  <px-select v-model="formValue.facCode" placeholder="请选择归属地块" filterable clearable @change="clearSparePartsTable">
                    <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.source === 'back'" :span="8">
                <px-form-item label="关联出库单号" prop="outNum">
                  <px-select v-model="formValue.outNum" placeholder="请选择关联出库单号" filterable clearable @change="outNumChange">
                    <px-option v-for="item in outNumList" :key="item.id" :label="item.outNum" :value="item.outNum" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.source === 'buy'" :span="8">
                <px-form-item label="采购单号" prop="billNum">
                  <px-input v-model="formValue.billNum" placeholder="请输入采购单号" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.source === 'buy'" :span="8">
                <px-form-item label="供应商" prop="supplier">
                  <px-input v-model="formValue.supplier" placeholder="请先选择采购单号" maxlength="50" clearable :disabled="!formValue.billNum" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="入库人员" prop="inOperateName">
                  <px-input v-model="formValue.inOperateName" placeholder="自动带出入库人员" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="入库审核人" prop="approverId">
                  <px-select-v2
                    v-model="formValue.approverId"
                    filterable
                    clearable
                    :options="approverIdList"
                    placeholder="请选择入库审核人"
                    @change="approverIdChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="备注" prop="remark">
                  <px-input
                    v-model="formValue.remark"
                    placeholder="请输入备注"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 6 }"
                    maxlength="1000"
                    clearable
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="入库明细">
          <template v-slot:content>
            <div v-if="formValue.source === 'buy'" class="btn-row">
              <px-button type="primary" plain icon="Plus" @click="addSpareParts" style="margin-right: 8px">添加</px-button>
              <px-button type="primary" plain @click="templateDownload" style="margin-right: 8px">下载模板</px-button>
              <BatchUpload
                url="/ifp/erc/api/v1/sparePart/inOutImportData"
                :needResponse="true"
                :facCode="formValue.facCode"
                @updateUploadPage="addImportData"
                title="导入"
              />
              <px-tooltip content="仅支持导入已选”归属地块”下的备件" placement="top">
                <px-icon style="margin: 8px 8px 0 -6px"><QuestionFilled /></px-icon>
              </px-tooltip>
              <px-button type="danger" plain style="margin-right: 8px" @click="batchDelete">批量删除</px-button>
            </div>
            <px-table :data="formValue.tableData" class="equip-table" size="small" max-height="400" border @selection-change="selectionChange">
              <px-table-column type="selection" width="50" align="center" fixed="left" />
              <px-table-column type="index" label="序号" width="80" align="center" fixed="left" />
              <px-table-column
                v-for="(item, index) in tableColumns"
                :key="index"
                :label="item.label"
                :min-width="item.minWidth"
                :align="item.align"
                :show-overflow-tooltip="item.showOverflowTooltip"
                :fixed="item.fixed"
              >
                <template #default="scope">
                  <div v-if="item.quantity && formValue.source === 'buy'">
                    <px-input-number v-model.number="scope.row.quantity" :max="9999" :min="0" size="small" />
                  </div>
                  <div v-else-if="item.quantity && formValue.source === 'back'">
                    {{ scope.row.quantity || "-" }}
                  </div>
                  <div v-else-if="item.returnQuantity && formValue.source === 'back'">
                    <px-input-number v-model.number="scope.row.returnQuantity" :min="0" :max="scope.row.quantity" size="small" />
                  </div>
                  <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
                </template>
              </px-table-column>
              <px-table-column v-if="formValue.source === 'buy'" fixed="right" label="操作" width="60" align="center">
                <template #default="scope">
                  <px-button link type="danger" icon="Delete" @click="handleDelete(scope.$index)" />
                </template>
              </px-table-column>
            </px-table>
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
                width: 100vw;
                height: 40px;
                padding: 0 12px 0 16px;
                margin: -6px 0 16px;
                background: #ecf5ff;
                border-radius: 4px;
              "
            >
              <div style="font-size: 14px; color: rgb(0 0 0 / 80%)">
                已选<span style="color: #3b82f6">{{ selectIds.length }}</span>
              </div>
              <div>
                <span>批量设置入库量</span>
                <px-input-number
                  v-model.number="quantityNumber"
                  style="margin-left: 20px"
                  :max="9999"
                  :min="0"
                  size="small"
                  :disabled="selectIds.length === 0"
                  @change="batchSetQuantityNumber"
                />
              </div>
            </div>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">提交</px-button>
    </div>
  </div>
  <!-- 选择备件弹窗 -->
  <AddSparePartsDialog :visible="dialogVisible" :facCodeData="formValue.facCode" @closeDialog="dialogVisible = false" @addTableRow="addTableRow" />
</template>
<script setup lang="ts">
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, ref, toRefs, watch, getCurrentInstance } from "vue";
import AddSparePartsDialog from "../../components/AddSparePartsDialog.vue";
import BatchUpload from "./BatchUpload.vue";
import { queryDictData } from "@/api/erc/common";
import {
  addSparePartsWarehousing,
  editSparePartsWarehousing,
  getInventoryOut,
  getSparePartsWarehousing,
  querySparePartsOutbound,
  querySparePartsWarehousingNum
} from "@/api/erc/spareParts";
import { cloneDeep, isEqual } from "@pureadmin/utils";
const { proxy }: any = getCurrentInstance();

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "addType", "drawerType", "sparePartsId", "userId"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {},
  approverIdList: [],
  facCodeList: [],
  tableColumns: [],
  outNumList: [],
  selectIds: [],
  quantityNumber: 0,
  dialogVisible: false,
  differContent: null
});
const { formValue, approverIdList, facCodeList, tableColumns, outNumList, selectIds, quantityNumber, dialogVisible, differContent } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  backReason: [{ required: true, message: "还回原因不能为空", trigger: "blur" }],
  outNum: [{ required: true, message: "关联出库单号不能为空", trigger: "blur" }],
  sourceDesc: [{ required: true, message: "入库类型不能为空", trigger: "blur" }],
  inNum: [{ required: true, message: "入库单号不能为空", trigger: "blur" }],
  inName: [{ required: true, message: "入库主题不能为空", trigger: "blur" }],
  facCode: [{ required: true, message: "归属地块不能为空", trigger: "blur" }],
  approverId: [{ required: true, message: "入库审批人不能为空", trigger: "change" }]
}));

const tagColorList = {
  pass: "#10B981",
  approving: "#F59E0B",
  reject: "#EF4444",
  not_pass: "#9254DE"
};

const tagBorderColorList = {
  pass: "#B7EAD9",
  approving: "#FCE2B6",
  reject: "#FAC7C7",
  not_pass: "#DDC2FF"
};

const tagBgColorList = {
  pass: "#E8F8F3",
  approving: "#FEF5E6",
  reject: "#FEECEC",
  not_pass: "#F2E7FF"
};

// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value?.resetFields();
    selectIds.value = [];
    querySelect();
    if (props.drawerType === "add") {
      const data = await querySparePartsWarehousingNum({});
      formValue.value = {};
      formValue.value.inNum = data;
      formValue.value.source = props.addType;
      if (formValue.value.source === "buy") {
        formValue.value.sourceDesc = "采购";
      } else if (formValue.value.source === "back") {
        formValue.value.sourceDesc = "领用退回";
      }
      formValue.value.inOperateId = props.userId;
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      formValue.value.inOperateName = userInfo.username + "-" + userInfo.realName;
      formValue.value.tableData = [];
      delete formValue.value.id;
    } else if (props.drawerType === "edit") {
      await getDetail();
    }
    if (formValue.value.source === "buy") {
      tableColumns.value = [
        { prop: "facCodeDesc", label: "归属地块", minWidth: "100", showOverflowTooltip: true, fixed: "left" },
        { prop: "sparePartName", label: "备件名称", minWidth: "180", showOverflowTooltip: true },
        { prop: "eqpTypeCodeDesc", label: "备件类型", minWidth: "180", showOverflowTooltip: true },
        { prop: "specification", label: "规格型号", minWidth: "150", showOverflowTooltip: true },
        { prop: "brandVal", label: "品牌", minWidth: "100", showOverflowTooltip: true },
        { prop: "sparePartUnit", label: "单位", minWidth: "80", showOverflowTooltip: true },
        { prop: "currentStock", label: "当前库存", minWidth: "80", showOverflowTooltip: true },
        { prop: "positionCode", label: "存放位置", minWidth: "120", showOverflowTooltip: true },
        { prop: "quantity", label: "本次入库量", minWidth: "120", showOverflowTooltip: true, fixed: "right", quantity: true }
      ];
    } else if (formValue.value.source === "back") {
      tableColumns.value = [
        { prop: "facCodeDesc", label: "归属地块", minWidth: "100", showOverflowTooltip: true, fixed: "left" },
        { prop: "sparePartName", label: "备件名称", minWidth: "180", showOverflowTooltip: true },
        { prop: "eqpTypeCodeDesc", label: "备件类型", minWidth: "180", showOverflowTooltip: true },
        { prop: "specification", label: "规格型号", minWidth: "150", showOverflowTooltip: true },
        { prop: "brandVal", label: "品牌", minWidth: "100", showOverflowTooltip: true },
        { prop: "sparePartUnit", label: "单位", minWidth: "80", showOverflowTooltip: true },
        { prop: "positionCode", label: "存放位置", minWidth: "120", showOverflowTooltip: true },
        { prop: "quantity", label: "出库数量", minWidth: "120", showOverflowTooltip: true, quantity: true },
        { prop: "returnQuantity", label: "还回数量", minWidth: "120", showOverflowTooltip: true, fixed: "right", returnQuantity: true }
      ];
    }
  } else {
    formValue.value = {};
  }
  differContent.value = cloneDeep(formValue.value);
});
// 获取下拉框
const querySelect = async () => {
  const arr = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  approverIdList.value = arr.filter(item => {
    return item.userId !== userInfo.userId;
  });
  facCodeList.value = await queryDictData({ typeCode: "ERC_FACTORY_AREA" });
  const params = {
    pageNum: 1,
    pageSize: 9999,
    approvalStatus: "pass",
    facCode: formValue.value.facCode
  };
  const data = await querySparePartsOutbound(params);
  outNumList.value = data?.data || [];
};
// 获取入库明细table
const outNumChange = async val => {
  formValue.value.tableData = [];
  formValue.value.tableData = await getInventoryOut(val);
  if (formValue.value.tableData && formValue.value.tableData.length > 0) {
    formValue.value.tableData.forEach(item => {
      item.returnQuantity = 0;
    });
  } else {
    PxMessage.warning("未能获取到设备关联备件");
  }
};
// 获取审批人名称
const approverIdChange = val => {
  const arr = approverIdList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.approverName = arr[0].label;
  }
};
// 清空备件表格
const clearSparePartsTable = () => {
  if (formValue.value.tableData && formValue.value.tableData.length > 0) {
    PxMessage.warning("归属地块发生变化，选中的备件已被清空，请重新添加！");
    formValue.value.tableData = [];
  }
};
// 获取详情接口
const getDetail = async () => {
  const params = {
    id: props.sparePartsId
  };
  const data = await getSparePartsWarehousing(params);
  formValue.value.id = props.sparePartsId;
  formValue.value.approvalStatus = data.approvalStatus;
  formValue.value.approvalStatusDesc = data.approvalStatusDesc;
  formValue.value.source = data.source;
  formValue.value.sourceDesc = data.sourceDesc;
  formValue.value.inNum = data.inNum;
  formValue.value.inName = data.inName;
  formValue.value.facCode = data.facCode;
  formValue.value.inOperateName = data.inOperateName;
  formValue.value.inOperateId = data.inOperateId;
  formValue.value.approverId = data.approverId;
  formValue.value.approverName = data.approverName;
  formValue.value.remark = data.remark;
  formValue.value.tableData = data.sparePartInventoryDTOList;
  if (formValue.value.source === "buy") {
    formValue.value.billNum = data.billNum;
    formValue.value.supplier = data.supplier;
  } else if (formValue.value.source === "back") {
    formValue.value.backReason = data.backReason;
    formValue.value.outNum = data.outNum;
  }
  differContent.value = cloneDeep(formValue.value);
};
// 导入按钮
const addImportData = res => {
  if (res?.data && res?.data.length > 0) {
    const arr = mergeArraysOptimized(formValue.value.tableData, res?.data);
    formValue.value.tableData = arr.filter(item => item.facCode === formValue.value.facCode);
    if (arr?.length !== formValue.value.tableData?.length) {
      PxMessage.success("导入成功，如包含不属于当前所选归属地块的备件，系统会自动过滤");
    } else {
      PxMessage.success("导入成功");
    }
  }
};
// 模版下载按钮
const templateDownload = async () => {
  proxy.download("get", "/erc/api/v1/sparePart/inOutTemplateDownLoad", {}, "备件入库信息模板.xlsx");
};
// 手动添加备件
const addSpareParts = () => {
  if (!formValue.value.facCode) {
    PxMessage.warning("请选择归属地块后操作");
    return;
  }
  dialogVisible.value = true;
};
// 表格多选框选中-批量删除使用
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
    }
  });
  quantityNumber.value = 0;
};
// 删除表格某一行
const handleDelete = (index: any) => {
  formValue.value.tableData.splice(index, 1);
};
// 批量设置number
const batchSetQuantityNumber = () => {
  if (formValue.value.source === "buy") {
    selectIds.value.forEach(val => {
      formValue.value.tableData.forEach((v, i) => {
        if (val === v.id) {
          v.quantity = quantityNumber.value;
        }
      });
    });
  } else if (formValue.value.source === "back") {
    selectIds.value.forEach(val => {
      formValue.value.tableData.forEach((v, i) => {
        if (val === v.id) {
          v.returnQuantity = quantityNumber.value;
        }
      });
    });
  }
};
// 批量删除
const batchDelete = () => {
  if (selectIds.value.length == 0) {
    PxMessage.warning("请选择备件后操作");
    return;
  }
  selectIds.value.forEach(val => {
    formValue.value.tableData.forEach((v, i) => {
      if (val === v.id) {
        formValue.value.tableData.splice(i, 1);
      }
    });
  });
};
// 返回主页面
const backMainPage = () => {
  const differCont = cloneDeep(formValue.value);
  if (isEqual(differContent.value, differCont)) {
    formRef.value?.resetFields();
    differContent.value = null;
    emits("backMainPage");
    return;
  }
  PxMessageBox.confirm("内容未保存，确认退出此入库单吗", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      formRef.value?.resetFields();
      differContent.value = null;
      emits("backMainPage");
    })
    .catch(() => {});
};
// 选择备件后添加到表格数据
const addTableRow = val => {
  if (val && val.length > 0) {
    const arr = [];
    formValue.value.tableData.forEach(item => {
      arr.push(item.id);
    });
    const arr2 = [];
    val.forEach(item => {
      if (!arr.includes(item.id)) {
        arr2.push(item);
      }
    });
    formValue.value.tableData = [...arr2, ...formValue.value.tableData];
  }
};
// 判断入库量都有值，不为0或者"""
const judgeQuantity = () => {
  if (formValue.value.tableData.length > 0) {
    const arr = [];
    formValue.value.tableData.forEach(item => {
      arr.push(item.quantity);
    });
    if (formValue.value.source === "buy") {
      return arr.every((value, index) => {
        return value != "";
      });
    } else if (formValue.value.source === "back") {
      return arr.every((value, index) => {
        return value != 0 && value != "";
      });
    }
  } else {
    return false;
  }
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (formValue.value.tableData && formValue.value.tableData.length > 0) {
        if (!judgeQuantity()) {
          PxMessage.error("入库量不能为空");
          return;
        }
        const arr = [];
        if (formValue.value.source === "buy") {
          formValue.value.tableData.forEach(item => {
            arr.push({
              parePartId: item.id,
              quantity: item.quantity
            });
          });
        } else if (formValue.value.source === "back") {
          formValue.value.tableData.forEach(item => {
            arr.push({
              parePartId: item.id,
              quantity: item.returnQuantity
            });
          });
        }
        formValue.value.inventoryDetailList = arr;
        const params = formValue.value;
        PxMessageBox.confirm("确认提交入库单吗", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
          draggable: true
        })
          .then(async () => {
            if (props.drawerType === "add") {
              await addSparePartsWarehousing(params);
              PxMessage.success("新增成功");
              emits("backMainPage");
              emits("queryTable");
            } else if (props.drawerType === "edit") {
              await editSparePartsWarehousing(params);
              PxMessage.success("编辑成功");
              emits("backMainPage");
              emits("queryTable");
            }
          })
          .catch(() => {});
      } else {
        PxMessage.error("备件列表不能为空");
      }
    }
  });
};
const mergeArraysOptimized = (a, b) => {
  // 1. 创建 a 的 ID 集合
  const aIds = new Set(a.map(item => item.id));

  // 2. 分离 b：独有对象 vs 替换对象
  const uniqueB = [];
  const replaceMap = new Map();

  b.forEach(item => {
    if (aIds.has(item.id)) {
      replaceMap.set(item.id, item);
    } else {
      uniqueB.push(item);
    }
  });

  // 3. 创建更新后的 a
  const updatedA = a.map(item => (replaceMap.has(item.id) ? replaceMap.get(item.id) : item));

  // 4. 合并结果
  return [...uniqueB, ...updatedA];
};
</script>
<style lang="scss" scoped>
@import url("@/views/erc/scss/add-detail.scss");
.btn-row {
  display: flex;
  margin-bottom: 8px;
  .px-button + .px-button {
    margin-left: 0;
  }
}
</style>
